#include "UpdateCommand.h"


UpdateCommand::UpdateCommand(SQLSystem* sql): Command(sql)
{
}


UpdateCommand::~UpdateCommand(void)
{
}

// update ebook set url = "www.google.com" where name = "book"
int UpdateCommand::execute(const string &str)
{
	vector<Row *> selectedRows;
	vector<string> columnsToDisplay;
	bool allColumn=false;
	Table* table;
	SQLSystem* system= getSystem();
	typedef tokenizer<char_separator<char> > token;
	char_separator<char> sep(" ",",",drop_empty_tokens);
	token tok(str, sep);
	token::iterator tok_iter= tok.begin();
	++tok_iter;
	if(tok_iter == tok.end())	
		return false;

	string tableName = *tok_iter;
	
	++tok_iter; // set
	++tok_iter; // colname
	string colName = *tok_iter;

	// value of column
	++tok_iter; // = 
	++tok_iter; // value
	string colValue  = *tok_iter;

	colValue = boost::algorithm::erase_all_copy(colValue, "\"");
	
	Table *t = sql->getTableByName(tableName);
	int colIndex  = t->getColumnIndex(colName);
	
	if( t == NULL )
	{
		cout << "TABLE DOES NOT EXIST\n";
		return false;
	}
	
	if((int) str.find("where") > 0 ) 
	{
		// handle where 


		++tok_iter; // where
	
		++tok_iter; // colName in condition
		string conColName = *tok_iter;
			
		int conColIndex = t->getColumnIndex(conColName);

		++tok_iter; // = 
		++tok_iter; // condition value
		string conValue = *tok_iter;
		// loop all row, check col with conValue

		conValue = boost::algorithm::erase_all_copy(conValue, "\"");
		
		vector<Row*> rows = t->getRows();
		vector<Cell*> cells ;
	
		for( int i=0; i< (int) rows.size(); i++)
		{
		
			Row *row = rows[i];
			vector<Cell*> cells =  row->getCells();
			Cell *conCol = cells[conColIndex];
			VarcharCell* vCell= dynamic_cast<VarcharCell *>(conCol);
		
			if( vCell->getData() == conValue ) {
				// update date for cell
				Cell *upCol = cells[colIndex];
				VarcharCell* upCell = dynamic_cast<VarcharCell *>(upCol);
				upCell->setData(colValue);
			}
		}
	}else {
		// update all rows
	
		vector<Row*> rows = t->getRows();
		
		for( int i=0; i< (int) rows.size(); i++)
		{
			cout << i;
			Row *row = rows[i];
			vector<Cell*> cells =  row->getCells();
			Cell *upCol = cells[colIndex];
			VarcharCell* vPathCell= dynamic_cast<VarcharCell *>(upCol);
			vPathCell->setData(colValue);
		}
	 }

	return true;
}
